﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Cryomancer.WPF.CustomControls
{
	[TemplatePart(Name="Part_CloseButton", Type=typeof(Button))]
	public class TabItemClosable : TabItem
	{
		#region Events
		
		#region Close Event Code
		public static RoutedEvent CloseEvent;
		public static RoutedEvent PreviewCloseEvent;

		public event RoutedEventHandler Close
		{
			add    { AddHandler(CloseEvent, value); }
			remove { RemoveHandler(CloseEvent, value); }
		}

		public event RoutedEventHandler PreviewClose
		{
			add    { AddHandler(PreviewCloseEvent, value); }
			remove { RemoveHandler(PreviewCloseEvent, value); }
		}
		#endregion	

		#endregion

		#region Members
		#endregion

		#region Properties
		#endregion

		#region C'Tors and other object lifetime methods
		public TabItemClosable()
		{

		}

		static TabItemClosable()
		{
			CloseEvent = EventManager.RegisterRoutedEvent(
				"Close",
				RoutingStrategy.Bubble,
				typeof(RoutedEventHandler),
				typeof(TabItemClosable));

			PreviewCloseEvent = EventManager.RegisterRoutedEvent(
				"PreviewClose",
				RoutingStrategy.Tunnel,
				typeof(RoutedEventHandler),
				typeof(TabItemClosable));

			DefaultStyleKeyProperty.OverrideMetadata(typeof(TabItemClosable), new FrameworkPropertyMetadata(typeof(TabItemClosable)));
		}
		#endregion

		#region Methods

		#region Control Overrides
		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();

			//Tie the close button's click event to the Close event.
			Button closeButton = GetTemplateChild("Part_CloseButton") as Button;
			closeButton.Click += CloseButton_Click;
		}
		#endregion

		#region Private Methods
		protected virtual void OnClose()
		{
			RoutedEventArgs args = new RoutedEventArgs(PreviewCloseEvent);
			RaiseEvent(args);
			if (!args.Handled)
			{
				//Removing the tab disposes it, and removes all of the event handling.
				//So, just make it invisible before raising the close event, and THEN
				//close it after all handlers are finished.
				this.Visibility = Visibility.Collapsed;

				RaiseEvent(new RoutedEventArgs(CloseEvent));

				RemoveTab();
			}
		}

		private void RemoveTab()
		{
			TabControl control = this.Parent as TabControl;
			if (control != null)
			{
				control.Items.Remove(this);
			}
		}
		#endregion

		#endregion

		#region Event Handlers
		void CloseButton_Click(object sender, RoutedEventArgs e)
		{
			OnClose();
		}
		#endregion
	}
}
